package model

import (
	"errors"
	"gorm.io/gorm"
	"ppa/init/mysql"
)

type NftTransient struct {
	ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
	HashTransaction  string  `json:"hash_transaction" form:"hash_transaction"  gorm:"size:256;default:'NULL'"`
	NftId uint `json:"nft_id"  form:"nft_id" `
	FromUserId uint `json:"from_user_id" form:"from_user_id"`
	ToUserId uint `json:"to_user_id" form:"to_user_id"`
	TransientPrice float64 `json:"transient_price"  form:"transient_price" gorm:"default:0"`
	TransactionState uint8 `json:"transaction_state" form:"transaction_state" gorm:"default:0"` //交易类型0创建1上架2是交易3下架
	CreateTime uint `json:"create_time" gorm:"autoCreateTime"`
	FromUser User `json:"form_user" gorm:"ForeignKey:FromUserId;AssociationForeignKey:UserId"`
	ToUser User `json:"to_user" gorm:"ForeignKey:ToUserId;AssociationForeignKey:UserId"`
}

func (nftTransient *NftTransient) GetNftTransient() (*[]NftTransient, error)  {
	var resNftTransient *[]NftTransient
	err := mysql.SqlDB.Preload("FromUser").Preload("ToUser").Where(nftTransient).Find(&resNftTransient).Error
	if err != nil || errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, errors.New("未查询到数据存在")
	}
	return resNftTransient, nil
}

// SetNftTransient 添加交易记录(批量)
func SetNftTransient(nftTransient []NftTransient,tx *gorm.DB) ([]NftTransient, error)  {
	db := mysql.SqlDB
	if tx != nil {
		db = tx
	}
	err := db.Create(&nftTransient).Error
	if err != nil {
		return nil, err
	}
	return nftTransient, nil
}

type ResData struct {
	CountTransient int
	NftId int
}
func GetNftTransientTop(Offset, Limit int) []int {
	var resData []ResData
	var nftList []int
	mysql.SqlDB.Table("ppa_nft_transient").Limit(Limit).Offset(Offset).Select("count(*) as count_transient,nft_id").Joins("left join ppa_nft on ppa_nft.id =  ppa_nft_transient.nft_id").Where("nft_state != 0").Group("nft_id").Order("count_transient DESC").Scan(&resData)
	for _,v := range resData {
		nftList = append(nftList,v.NftId)
	}
	return nftList
}